package com.zzyq.pc.common.plugin.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.CodeMsg;
import com.zzyq.pc.common.plugin.shiro.TokenManager;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.web.user.model.User;

/**
 * 
 * <p>
 * 
 * @Title: LoginFilter.java
 * @Description: 验证登录过滤器
 * @author: Sywd丶吴迪
 * @date: 2017年8月29日 下午5:27:21
 * @version V1.0
 *          <p>
 */
public class LoginFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {
        try {
            User user = TokenManager.getUser();
            if (null != user || isLoginRequest(request, response)) {
                return Boolean.TRUE;
            }
            if (HttpUtils.isAjax(request)) {// AJAX请求
                String str = HttpUtils.formatData(new StandardDataFormat(), CodeMsg.CODE_LOGIN_REQUEST,
                        CodeMsg.MSG_LOGIN_REQUEST, null);
                HttpUtils.out(response, str);
            } else {
                WebUtils.issueRedirect(request, response, HttpUtils.LOGIN_URL);
                // request.getRequestDispatcher(HttpUtils.LOGIN_URL).forward(request,
                // response);
            }
        } catch (Exception e) {

        }
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // 保存Request和Response 到登录后的链接
//        saveRequestAndRedirectToLogin(request, response);
        return Boolean.FALSE;
    }

}
